package cn.yuanqiao.cqbc.yqCarrierManage.service.impl;

import cn.hutool.core.util.ZipUtil;
import cn.yuanqiao.feignService.RemoteCommonService;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.cqbc.common.mapper.MapperToolsMapper;
import cn.yuanqiao.cqbc.yqCarrierManage.domain.YqCarrierManage;
import cn.yuanqiao.cqbc.yqCarrierManage.domain.YqCarriermanageDetail;
import cn.yuanqiao.cqbc.yqCarrierManage.mapper.YqCarrierManageMapper;
import cn.yuanqiao.cqbc.yqCarrierManage.mapper.YqCarriermanageDetailMapper;
import cn.yuanqiao.cqbc.yqCarrierManage.service.YqCarrierManageService;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 载体管理 服务实现类
 * </p>
 *
 * @author lyk
 * @since 2022-11-17
 */
@Service
public class YqCarrierManageServiceImpl implements YqCarrierManageService {

//    @Resource
//    private DictMapper sysDictDao;

    @Autowired
    private YqCarrierManageMapper yqCarrierManageMapper;
    @Autowired
    private YqCarriermanageDetailMapper yqCarriermanageDetailMapper;
    @Resource
    private MapperToolsMapper DbTool;
    @Autowired
    private RemoteCommonService remoteCommonService;
    @Override
    public int add(YqCarrierManage param){
        //YqCarrierManage entity = getEntity(param);
        //this.save(entity);
        String tenantCode = SecurityUtils.getTenantCode();
        param.setTenantCode(tenantCode);
        return yqCarrierManageMapper.add(param);
    }

    @Override
    public YqCarrierManage getById(Long id) {
        return yqCarrierManageMapper.getById(id);
    }

    @Override
    @Transactional
    public int detection(YqCarrierManage yqCarrierManageParam) {
        YqCarriermanageDetail yqCarriermanageDetail = new YqCarriermanageDetail();
        yqCarriermanageDetail.setBatchId(getRandomBatchNum());
        yqCarriermanageDetail.setCode(yqCarrierManageParam.getCode());
        yqCarriermanageDetail.setSuccess("0");
        yqCarriermanageDetail.setName(yqCarrierManageParam.getName());
        yqCarriermanageDetail.setIsRunning("1");
        String tenantCode = SecurityUtils.getTenantCode();
        yqCarriermanageDetail.setTenantCode(tenantCode);
        ArrayList<File> files = new ArrayList<>();
        ArrayList<File> search = search(yqCarrierManageParam.getSavePath(), files);
        int i=1;

        for (File file : search) {
            //Map<String, Object> resultMap = new HashMap<>();
            //Object clone = yqCarriermanageDetail.clone();
            YqCarriermanageDetail yqCarriermanageDetail1 = new YqCarriermanageDetail();
            long l = SnowflakeIdGenerator.generateId();
            yqCarriermanageDetail.setId(l);
            BeanUtils.copyProperties(yqCarriermanageDetail,yqCarriermanageDetail1);
            yqCarriermanageDetailMapper.insert(yqCarriermanageDetail1);
            Map<String,Object> categoryIdByMap = null;
            try {
                //String zipPath = configService.getConfigByKeyTenantCode("HDDA_EEP_PATH",tenantCode).getData();
                //if(StringUtils.isEmpty(zipPath) || "null".equals(zipPath)){
                //    throw new ServiceException("系统参数HDDA_EEP_PATH未配置");
                //}
                //String zipPath =  ConstantsContext.getParamValueByCode("HDDA_EEP_PATH")+"/JS/TEMP/";
                //zipPath += UUID.randomUUID();
                //不知道解压缩是同步还是异步,待测试
                //String hd_charset_zip = configService.getConfigByKeyTenantCode("HD_CHARSET_ZIP", tenantCode).getData();
                //if(StringUtils.isEmpty(hd_charset_zip) || "null".equals(hd_charset_zip)){
                //    throw new ServiceException("系统参数HD_CHARSET_ZIP未配置");
                //}
                //ZipUtil.unzip(file.getPath(), zipPath, Charset.forName(hd_charset_zip));
                String name = file.getName();
                if(name.contains(".")){
                    name = name.substring(0,name.lastIndexOf("."));
                }
                JSONObject json=new JSONObject(1<<3);
                json.put("path",file.getPath());
                String categoryId = DbTool.getSingle("select category from yq_data_manage where dh = '" + name + "' and isdel=0 and tenant_code = '" + tenantCode + "'");
                String code = DbTool.getSingle("select IDENTIFICATION from " + tenantCode + "_YQ_DETECTION_SCHEME where categoryid = " + categoryId);
                json.put("code",code);
                json.put("link","2");
                json.put("lx","1");
                AjaxResult data = remoteCommonService.detectionPackage(json);
                int failNum= (Integer) data.get("failNum");
                String sxId=(String) data.get("sxId");
                yqCarriermanageDetail1.setSuccess(failNum>0?"0":"1");
                //yqCarriermanageDetail1.setSuccess(check.get("code").toString().equals("200")?"1":"0");
                yqCarriermanageDetail1.setFourCheckId(sxId);
                /*Map<String, Object> zipMap = EEPUtil.getFileString(zipPath);
                categoryIdByMap = eepUtil.getCategoryIdByMap(zipMap );
                HashMap<String, Object> check = changQiBaoCunCheck.check(file.getPath(), categoryIdByMap.get("categoryId").toString(), "6"
                        , categoryIdByMap.get("fondsCode").toString(), ConstantsContext.getCharsetFroXML(),ConstantsContext.getParamValueByCode("HD_CHECK_REGSTR"));
                yqCarriermanageDetail1.setSuccess(check.get("code").toString().equals("200")?"1":"0");
                yqCarriermanageDetail1.setFourCheckId(check.get("record_id").toString());*/
            } catch (Exception e) {
                i=0;
                e.printStackTrace();
                yqCarriermanageDetail1.setSuccess("0");
            } finally {
                yqCarriermanageDetail1.setIsRunning("0");
                yqCarriermanageDetailMapper.updateById(yqCarriermanageDetail1);
            }
        }
        return i;
    }

    public static String getRandomBatchNum() {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

        String format = dateFormat.format(new Date());

        int max=24;

        int min=24;

        Random random = new Random();

        int s = random.nextInt(max)%(max-min+1) + min;

        StringBuffer buffer =new StringBuffer();

        for(int i=0;i<=s;i++){

            Integer val = (int)(Math.random()*9+1);

            buffer.append(val.toString());

        }

        return format+buffer.toString();

    }


    public static ArrayList<File> search(String path,ArrayList<File> files)
    {
        File dir = new File(path);
        //获取e盘下所有的文件或文件夹对象
        File[] subFiles = dir.listFiles();

        if (null!=subFiles){
            for (File subFile : subFiles) {
                //文件夹则递归寻找，后缀为jpg文件则输出名字
                if (subFile.isDirectory())
                {
                    files = search(subFile.getAbsolutePath(),files);
                } else if(subFile.isFile() && subFile.getName().endsWith(".zip")) {
                    System.out.println(subFile.getName());
                    files.add(subFile);
                }
            }
        }
        return files;
    }
    @Override
    public int delete(Long id){
        return yqCarrierManageMapper.delete(id);
    }

    @Override
    public int update(YqCarrierManage param){
        /*YqCarrierManage oldEntity = getOldEntity(param);
        YqCarrierManage newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);*/
        return yqCarrierManageMapper.update(param);
    }

    /*@Override
    public YqCarrierManage findBySpec(YqCarrierManage param){
        return this.baseMapper.selectById(param.getId());
    }*/

    @Override
    public List<YqCarrierManage> findListBySpec(YqCarrierManage param){
        String tenantCode = SecurityUtils.getTenantCode();
        param.setTenantCode(tenantCode);
        return yqCarrierManageMapper.customList(param);
    }

    @Override
    public int getNumByCode(String code) {
        String tenantCode = SecurityUtils.getTenantCode();
        return yqCarrierManageMapper.getNumByCode(code,tenantCode);
    }

    /*@Override
    public LayuiPageInfo findPageBySpec(YqCarrierManage param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        List<YqCarrierManage> records = page.getRecords();
        //List<YqCarrierManage> newRecords = new ArrayList<>();
        List<Map<String, Object>> CARRIER_TYPE = sysDictDao.loadSysDictByCode("CARRIER_TYPE");
        Map<String,String> dictMap = new HashMap<String,String>();
        for (Map<String, Object> item : CARRIER_TYPE) {
            String code = item.get("CODE")==null?item.get("code").toString():item.get("CODE").toString();
            String name = item.get("NAME")==null?item.get("name").toString():item.get("NAME").toString();
            dictMap.put(code, name);
        }
        for (YqCarrierManage item : records) {
            item.setName(dictMap.get(item.getName()));
        }
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public int getNumByCode(String code) {
        return this.baseMapper.getNumByCode(code);
    }*/

    /*private Serializable getKey(YqCarrierManage param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private YqCarrierManage getOldEntity(YqCarrierManage param) {
        return this.getById(getKey(param));
    }

    private YqCarrierManage getEntity(YqCarrierManage param) {
        YqCarrierManage entity = new YqCarrierManage();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }*/

}
